import { defineComponent } from "vue";
import { useRouter } from "vue-router";
import { httpEvent } from "@/apis";
import { useToast } from "@/components/ui/toast/useToast";
import { useUserStore } from "@/stores/user";

export default defineComponent({
  setup() {
    const toast = useToast();
    const router = useRouter();
    const userStore = useUserStore();
    // 统一处理 http 事件
    // 在请求头中添加 token
    httpEvent.on("request", (options) => {
      if (userStore.isLogin()) {
        options.headers = {
          ...options.headers,
          Authorization: `Bearer ${userStore.token}`,
        };
      }
    });
    httpEvent.on("response", (ctx) => {
      const { message, success } = ctx.data;
      if (message) {
        if (success) {
          toast.success(message);
        } else toast.error(message);
      }
    });
    // 统一处理错误
    httpEvent.on("error", (err) => {
      const { response } = err;
      if (response) {
        // 401 登录过期
        if (response.status == 401) {
          // 用户登录过期，则将全局状态重置。
          userStore.logout();
          return router.push({ name: "login" });
        }
        const message = response.data?.message;
        if (message) {
          return toast.error(message, {
            title: "运行错误",
          });
        }
      }
      // 其他错误
      toast.error(err.message, {
        title: "服务器运行错误",
      });
    });
    // 返回渲染函数
    return () => false;
  },
});
